package repository;

import java.io.File;
import java.io.IOException;
import fileoperation.FileCreation;
import gitobject.GitObject;

public class Repository {
    private static String workTree;    //working directory
    private static String gitDir;    //jit repository path

    /**
     * Constructor
     */
    public Repository() throws IOException {
        if (gitDir.equals("")) {
            throw new IOException("The repository does not exist!");
        }
    }

    /**
     * Construct a new repository instance with certain path.
     * Constructor
     *
     * @param path
     * @throws IOException
     */
    public Repository(String path) throws IOException {
        workTree = path;
        gitDir = path + File.separator + ".jit";
        FileCreation.createFile(".", "workPath", workTree);
    }

    public static String getGitDir() throws IOException{
        gitDir = GitObject.getValue(new File("workPath")) + File.separator + ".jit";
        return gitDir;
    }

    public static String getWorkTree() throws IOException{
        workTree = GitObject.getValue(new File("workPath"));
        return workTree;
    }

    /**
     * Helper functions.
     *
     * @return
     */
    public boolean exist() {
        return new File(gitDir).exists();
    }

    public boolean isFile() {
        return new File(gitDir).isFile();
    }

    public boolean isDirectory() {
        return new File(gitDir).isDirectory();
    }


    /**
     * Create the repository and files and directories inside.
     *
     * @return boolean
     * @throws IOException
     */
    public void createRepo() throws IOException {
        FileCreation.createDirectory(workTree, ".jit");
        String[] directory = {"hooks", "info", "logs", "refs", "objects"};
        for (String s : directory) {
            FileCreation.createDirectory(gitDir, s);
        }
        FileCreation.createDirectory(gitDir + File.separator + "refs", "heads");
        FileCreation.createDirectory(gitDir + File.separator + "refs", "tags");
        FileCreation.createFile(gitDir, "HEAD", "ref: refs"+ File.separator + "heads" +File.separator+"master");
    }
}
